package com.cskaoyan.order.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * @program: csmall-practice
 * @description: 延迟取消订单的生产者
 * @author: Lexis
 * @create: 2022-05-23 19:13
 **/

@Slf4j
@Component
public class DelayOrderCancelProducer {

    DefaultMQProducer producer;

    @PostConstruct
    public void init() {
        producer = new DefaultMQProducer("delay_order_cancel_producer");

        producer.setNamesrvAddr("127.0.0.1:9876");

        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public boolean sendDelayOrderMessage(String orderId) {
        byte[] orderIdBytes = orderId.getBytes(StandardCharsets.UTF_8);

        Message message = new Message("delay_order_cancel", orderIdBytes);


        // 1  2  3  4  5
        // 1  5  10 30 60
        message.setDelayTimeLevel(5);

        SendResult send = null;

        try {
            send = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (send != null && SendStatus.SEND_OK.equals(send.getSendStatus())) {
            log.info("生产者发送成功");
            return true;
        }

        return false;
    }


}
